from typing import *
from math import inf


class Solution:

    def minimumSum(self, nums: List[int]) -> int:
        n = len(nums)
        f = [inf] * n
        mn = inf
        for i in range(n - 1, -1, -1):
            f[i] = mn
            mn = min(mn, nums[i])
        mn = inf
        ans = inf
        for i in range(n):
            if nums[i] > f[i] and nums[i] > mn:
                ans = min(ans, nums[i] + mn + f[i])
            mn = min(mn, nums[i])
        return ans if ans < inf else -1


s = Solution()
print(s.minimumSum([3, 1, 2]))
print(s.minimumSum([8, 6, 1, 5, 3]))
